 <?php
/**
 * Created by PhpStorm.
 * User: xiant_000
 * Date: 2018/11/12
 * Time: 7:30
 */

class AsyncMysql
{
    public $dbSource = '';
    /**
     * mysql 配置
     *
     * @var array
     */
    public $dbConfig = [];

    public function __construct()
    {
        $this->dbSource = new Swoole\Mysql;

        $this->dbConfig = [
            'host'  => '127.0.0.1',
            'port'  => 3360,
            'user'  => 'root',
            'password'  => 123456,
            'database'  => 'swoole',
            'charset'  => 'utf8',
        ];
    }

    public function update()
    {}

    public function add()
    {}

    /**
     * MySQL 执行逻辑
     *
     * @param $id
     * @param $username
     * @return bool
     */
    public function execute($id, $username)
    {
        // connect
        $this->dbSource->connect($this->dbConfig, function ($db, $result) {
            if ($result === false) {
                var_dump($db->connect_error);
            }

            $sql = "select * from test where id = 1";

            // $query
            $db->query($sql, function ($db, $result) {
                //
                // select => result返回的是 查询的结果内容

                if($result === false) {
                    // todo
                    var_dump($db->error);
                }elseif($result === true) {// add update delete
                    // todo
                    var_dump($db->affected_rows);
                }else {
                    print_r($result);
                }
                $db->close();
            });
        });
        return true;
    }
}

$obj = new AsyncMysql();
$obj->execute(1, 'singwa-11111');